package cn.edu.scau.controller;

import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.entity.Manager;
import cn.edu.scau.entity.Nurse;
import cn.edu.scau.entity.NurseConve;
import cn.edu.scau.service.ManagerService;
import cn.edu.scau.service.NurseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;

import java.util.List;


@Api(tags = "护士信息信息控制器")
@RestController
//@Controller
@RequestMapping(value = "nurse")
public class NurseController {
    @Autowired
    private NurseService nurseService;
    @Autowired
    private ManagerService managerService;
    /**
     * 显示所有护士信息页面
     * @return
     */
    @ApiOperation(value = "显示所有护士信息页面:数据存储在hospital中")
    @GetMapping(value = "/list")
    //@ResponseBody
    public ResultBean list(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Nurse> nurses=nurseService.selectAll();
        PageInfo<Nurse> pageInfo = new PageInfo<Nurse>(nurses);
        ResultBean r =new ResultBean(200,true,"查询所有护理级别信息成功~~~",pageInfo);
        return r;
    }
    public ResultBean detail(@PathVariable("userAccount") String userAccount){
        Manager manager = managerService.selectByUserAccount(userAccount);
        ResultBean r = new ResultBean(200, true, "查询成功", manager);
        //查不到
        if(manager==null) {
            r = new ResultBean(5008, false, "查询失败", null);
        }
        return r;
    }
    /**
     * 显示所护士根据编号，姓名模糊查询
     * 基于前后端分离
     * @param
     * @return
     */
    @ApiOperation(value = "显示所护士根据编号，姓名模糊查询,数据存储在hospital中")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query" ,name = "userId" , value = "用户编号",dataType = "int"),
            @ApiImplicitParam(paramType = "query" ,name = "nurseID" , value = "护士编号",dataType = "int"),
            @ApiImplicitParam(paramType = "query" ,name = "nursename" , value = "护士姓名",dataType = "String")
    })
    @GetMapping(value = "/find")
//    @ResponseBody
    public ResultBean find(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize,
            Integer userId,Integer nurseID,String nursename){
        PageHelper.startPage(pageNum, pageSize);
       List<Nurse> nurses = nurseService.findByIdUseidName(userId, nurseID, nursename);
        PageInfo<Nurse> pageInfo = new PageInfo<Nurse>(nurses);
        ResultBean r = new ResultBean(200,true,"模糊查询信息成功",pageInfo);

        return r;
    }
    /**
     * 删除相应id的护士信息,让其标志位失效
     * @param nurseid
     * @return
     */
    @ApiOperation(value = "删除相应id的护士信息")
    @DeleteMapping(value = "/delete/{nurseid}")
//    @ResponseBody
    public ResultBean delete(@PathVariable("nurseid") Integer nurseid){
        ResultBean r = null;
        Nurse nurse = nurseService.selectByPrimaryKey(nurseid);
        //修改有效位
        nurse.setNurseuseflag(false);
        boolean flag = nurseService.updateByPrimaryKeySelective(nurse);
        if(flag){
            r =new ResultBean(200,true,"删除成功",null);
        }else
        {
            r =new ResultBean(5005,false,"删除失败",null);
        }
        return r;
    }
    /**
     * 根据护士id查询护士信息
     * @param nurseid
     * @return
     */
    @ApiOperation(value = "根据护士id查询护士信息")
    @ApiImplicitParam(paramType = "path" ,name = "nurseid" , value = "护士id",dataType = "int")
    @ApiResponse(code = 200,message = "返回updatenurse页面,数据存储在office中")
    @GetMapping(value = "/{nurseid}")
//    @ResponseBody
    public ResultBean detail(@PathVariable("nurseid")Integer nurseid){
       Nurse nurse = nurseService.selectByPrimaryKey(nurseid);
        ResultBean r = new ResultBean(200, true, "查询成功", nurse);
        //查不到
        if(nurse==null) {
            r = new ResultBean(5008, false, "查询失败", null);
        }
        return r;
    }
    /**
     * 新增护士
     *
     * @return
     * @throws ParseException
     */
    @PostMapping(value = "/insert")
//    @ResponseBody
    public ResultBean insert(@Validated NurseConve nurseConve, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        Nurse nurse = Nurse.builder()
                .nurseid(null)
                .nursename(nurseConve.getNursename())
                .nurseage(Integer.valueOf(nurseConve.getNurseage()))
                .nursesex(nurseConve.getNursesex())
                .userid(Integer.valueOf(nurseConve.getUserid()))
                .nurseuseflag(true)
                .build();
        //用户并没有编入护士且用户还有效
        if(nurseService.selectByUserId(nurse.getUserid())==null&&managerService.selectByPrimaryKey(nurse.getUserid())!=null&&managerService.selectByPrimaryKey(nurse.getUserid()).getUserUseflag()) {
            boolean flag = nurseService.insert(nurse);
            if (flag) {

                r = new ResultBean(200, true, "增加成功\n新增护士编号为" + nurse.getNurseid(), null);
            } else {
                r = new ResultBean(5005, false, "增加失败", null);
            }
        }else{
            r = new ResultBean(5005, false, "该用户已经是护士，或者该用户不存在", null);
        }
        return r;
    }
    /**
     * 修改护士信息
     * @param nurseid

     * @return
     * @throws ParseException
     */
    @PutMapping(value = "/update/{nurseid}")
//    @ResponseBody
    public ResultBean update(@PathVariable("nurseid") String nurseid,@Validated NurseConve nurseConve, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        Nurse nurse = Nurse.builder()
                .nurseid(Integer.valueOf(nurseid))
                .nursename(nurseConve.getNursename())
                .nurseage(Integer.valueOf(nurseConve.getNurseage()))
                .nursesex(nurseConve.getNursesex())
                .userid(Integer.valueOf(nurseConve.getUserid()))
                .build();
        boolean flag = nurseService.updateByPrimaryKeySelective(nurse);
        if(flag){
            r =new ResultBean(200,true,"修改成功",null);
        }else
        {
            r =new ResultBean(5005,false,"修改失败",null);
        }
        return r;
    }
}
